package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.QuestionFormDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.QuestionAdminPageQuery;
import com.tianji.learning.domain.query.QuestionPageQuery;
import com.tianji.learning.domain.vo.QuestionAdminVO;
import com.tianji.learning.domain.vo.QuestionVO;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.learning.service.IInteractionReplyService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动提问的问题表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-02
 */
@Service
public class InteractionQuestionServiceImpl extends ServiceImpl<InteractionQuestionMapper, InteractionQuestion> implements IInteractionQuestionService {


    @Resource
    private IInteractionReplyService interactionReplyService;

    @Resource
    private UserClient userClient;

    @Override
    public void saveQuestion(QuestionFormDTO questionDTO) {
        Long user = UserContext.getUser();

        InteractionQuestion interactionQuestion = new InteractionQuestion();
        BeanUtils.copyProperties(questionDTO, interactionQuestion);

        interactionQuestion.setUserId(user);


        this.save(interactionQuestion);
    }

    @Override
    public PageDTO<QuestionVO> queryQuestionPage(QuestionPageQuery query) {
        //1.校验
        if (query.getCourseId() == null) {
            throw new BizIllegalException("课程id为空");
        }

        Long user = UserContext.getUser();

        //2.分页查询interaction_question
        Page<InteractionQuestion> questionPage = lambdaQuery()
                .eq(query.getOnlyMine(), InteractionQuestion::getUserId, user)
                .eq(InteractionQuestion::getCourseId, query.getCourseId())
                .eq(Objects.nonNull(query.getSectionId()), InteractionQuestion::getSectionId, query.getSectionId())
                .eq(InteractionQuestion::getHidden, false)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());

        List<InteractionQuestion> records = questionPage.getRecords();

        if (records == null || records.isEmpty()) {
            return PageDTO.empty(questionPage);
        }

        //3.查询最近一次回答内容
        Set<Long> userIds2 = new HashSet<>();
        Set<Long> userIds = records.stream()
                .filter(c -> c.getLatestAnswerId() != null)
                .map(InteractionQuestion::getUserId)
                .collect(Collectors.toSet());

        Map<Long,InteractionReply> replyMap = new HashMap<>();
        List<InteractionReply> interactionReplies = interactionReplyService.listByIds(userIds);
        //TODO 上述未忽略hidden属性

        for (InteractionReply interactionReply : interactionReplies) {
            if (!interactionReply.getAnonymity()) {
                userIds2.add(interactionReply.getUserId());
            }
            replyMap.put(interactionReply.getId(), interactionReply);
        }

        //4.查用户表获取用户信息

        for (InteractionQuestion record : records) {
            if (!record.getAnonymity()){
                userIds2.add(record.getUserId());
            }
        }
        List<UserDTO> userDTOS = userClient.queryUserByIds(userIds2);
        Map<Long, UserDTO> userDTOMap = userDTOS.stream().collect(Collectors.toMap(UserDTO::getId, c -> c));


        //x.封装vo
        List<QuestionVO> questionVOList = new ArrayList<>();
        for (InteractionQuestion record : records) {
            QuestionVO questionVO = BeanUtils.copyProperties(record, QuestionVO.class);

            if (!questionVO.getAnonymity()) {
                UserDTO userDTO = userDTOMap.get(record.getUserId());
                if (userDTO != null) {
                    questionVO.setUserName(userDTO.getName());
                    questionVO.setUserIcon(userDTO.getIcon());
                }

            }



            InteractionReply interactionReply = replyMap.get(record.getLatestAnswerId());
            if (interactionReply != null) {
                if (!interactionReply.getAnonymity()) {
                    UserDTO userDTO = userDTOMap.get(interactionReply.getUserId());
                    if (userDTO != null) {
                        questionVO.setUserName(userDTO.getName());
                    }
                }
                questionVO.setLatestReplyContent(interactionReply.getContent());
            }


            questionVOList.add(questionVO);

        }
        return PageDTO.of(questionPage, questionVOList);
    }

    @Override
    public QuestionVO queryQuestionById(Long id) {

        //1.查询问题基本信息
        InteractionQuestion interactionQuestion = this.getById(id);
        if (interactionQuestion == null) {
            throw new BizIllegalException("该问题不存在");
        }
        if (interactionQuestion.getHidden()) {
            return new QuestionVO();
        }


        //X.封装vo返回
        QuestionVO questionVO = new QuestionVO();
        BeanUtils.copyProperties(interactionQuestion, questionVO);


        //2.调用用户服务查询提问者昵称头像
        if (!interactionQuestion.getAnonymity()) {
            UserDTO userDTO = userClient.queryUserById(interactionQuestion.getUserId());
            questionVO.setUserName(userDTO.getName());
            questionVO.setUserIcon(userDTO.getIcon());
        }

        return questionVO;
    }




    /*
    * 管理端
    * */
    @Override
    public PageDTO<QuestionAdminVO> queryQuestionPageAdmin(QuestionAdminPageQuery query) {

        
        return null;
    }
}
